package com.zd.lib.http.gson;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.zd.lib.http.response.BaseEntity;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by zoudong on 16/7/24.
 *
 * @author zoudong
 * @version  1.0
 *  解析 json  统一格式，  先解析 code   code !=0 不解析 data
 *  防止  data  解析数据类型不同   而报错问题，
 */
public class JsonCommonDeserializer implements JsonDeserializer<BaseEntity<?>> {
    public static final String CODE = "code";
    public static final String MSG = "msg";
    public static final String DATA = "data";
    @Override
    public BaseEntity<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.isJsonObject()) {
            BaseEntity base = new BaseEntity();
            JsonObject object = json.getAsJsonObject();
            int code=-1;
            String msg = "服务器异常";
            if (object.has(CODE)) {
                code = object.get(CODE).getAsInt();
            }
            if (object.has(MSG)) {
                msg = object.get(MSG).getAsString();
            }

            base.setCode(code);
            base.setMsg(msg);
            if (base.SUCCESS()) {
                JsonElement data = object.get(DATA);
                if (!data.isJsonNull()) {
                    if (typeOfT instanceof ParameterizedType) {
                        Type itemType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];  // 获取泛型类型
                        //当服务器 返回  [] {}  不判断类型
                        if ((data.isJsonObject()&&data.getAsJsonObject().size()>0)||(data.isJsonArray()&&data.getAsJsonArray().size()>0)) {
                            base.setData(context.deserialize(data, itemType));
                        }
                    }
                }

            }

            return base;
        }
        return null;
    }
}
